package cn.edu.lingnan.servlet;

import cn.edu.lingnan.pojo.Student;
import cn.edu.lingnan.service.IStudentService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
@WebServlet("/admin/delStu")
public class DelStudent extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1
        String sid = req.getParameter("sid");
        String flag = req.getParameter("flag");
        boolean result;
        System.out.println("[Debug 049] the flag is value is " + flag);
        System.out.println("[Debug 050] the sid is value if " + sid);
        //2
        IStudentService service = new IStudentService();
        if(flag!=null){//删除多个记录
            int flag2;
            String[] allSid = sid.split(",");
            for (String oneSid:allSid//遍历获取一个学生flag标志的数组
            ) {//第一个循环，只要有一个标志位为1的，就跳转到错误页面
                Student student = new Student();
                student = service.findStudentById(Integer.parseInt(oneSid));
                flag2 = student.getFlag();
                if(flag2==1){//标志着该学生由于报名了某个竞赛项目，此时进行删除学生记录的诱会引起外键异常，跳转到错误页面处理
                    resp.sendRedirect("/admin/DelStuError.html");//发生异常要检查是否在竞赛记录表中存在记录
                    return;//只要被选中的多个学生记录中有一个是参加了竞赛，所有的学生记录都不能进行删除
                }

            }
            for (String oneSid : allSid) {
                result = service.delStudent(Integer.parseInt(oneSid));//执行多个记录删除
                if (!result) {
                    resp.sendRedirect("/admin/DelStuError.html");
                    return;
                }
            }
            resp.sendRedirect("/queryAllStu");
        }
        else {//否则删除单个记录
            result = service.delStudent(Integer.parseInt(sid));//getParameter拿到的是字符类型，本方法参数为int
            if(result){
                resp.sendRedirect("/queryAllStu");
            }else {
                resp.sendRedirect("/admin/DelStuError.html");
            }
        }
        //3

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
